/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package df.servlet.interfacefile;

import df.bean.db.conn.DBConn;
import df.bean.db.conn.DBConnection;
import df.bean.interfacefile.ImportExpenseBean;
import df.bean.interfacefile.ImportGuaranteeBean;
import df.bean.interfacefile.ImportNewMasterBean;
import df.bean.interfacefile.ImportTimeTableBean;
import df.bean.interfacefile.ImportTransactionArReceiptBean;
import df.bean.interfacefile.ImportTransactionBean;
import df.bean.interfacefile.ImportTransactionResultBean;
import df.bean.interfacefile.ImportExpenseExcelBean;
import df.bean.obj.util.JDate;
import df.bean.obj.util.Variables;
import java.io.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import javazoom.upload.*;
/**
 *
 * @author nopphadon
 */
public class ImportFileSrvl extends HttpServlet {
    HttpSession session;
    ImportTransactionBean it = new ImportTransactionBean();
    ImportNewMasterBean inmb = new ImportNewMasterBean();
    ImportTransactionResultBean idr = new ImportTransactionResultBean();
    ImportTransactionArReceiptBean iar = new ImportTransactionArReceiptBean();
    ImportGuaranteeBean igu = new ImportGuaranteeBean();
    ImportExpenseBean iex = new ImportExpenseBean();
    ImportExpenseExcelBean iee = new ImportExpenseExcelBean();
    ImportTimeTableBean itt = new ImportTimeTableBean();
    
    public void init() throws ServletException {
        super.init();
        /*
        con1 = new DBConnection();
        con1.connectToLocal();
        //con1.connectToServer();
        cdb = new DBConn(con1.getConnection());
        try {
            cdb.setStatement();
        } catch (Exception ex) {
            System.out.println(ex);
        }
        */
    }
    
    @Override
    public void destroy(){
        super.destroy();
        //con1.Close();
        //cdb.closeDB("");
    }

    private String getIP(String cond, String hospital) {
        String IP = null;
        DBConnection con = new DBConnection();
        con.connectToLocal();
        String query = "";
        query = "SELECT VALUE FROM CONFIG WHERE NAME='" + cond + "' AND HOSPITAL_CODE = '"+hospital+"'";
        ResultSet rs = null;
        rs = con.executeQuery(query);
        try {
            while (rs != null && rs.next()) {
                //IP = "\\\\" + rs.getString("VALUE").toString(); //for IP
                IP = "" + rs.getString("VALUE").toString(); //for Path
            }
            if (rs != null) {
                rs.close();
            }
        } catch (Exception err) {
        }
        con.Close();
        return IP;
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        //response.setContentType("text/xml; charset=UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        session = request.getSession(true);
        MultipartFormDataRequest mrequest = null;
        String filename = "";
        String source_file = "";
        String ip = "";
        String hospital_code = "";
        String dt = "";
        String user_id = "";
        String upload_path = "";
        //String upload_path = getServletConfig().getServletContext().getRealPath("")+"\\reports\\output\\";
        DBConnection con1 = new DBConnection();
        con1.connectToLocal();
        //con1.connectToServer();
        DBConn cdb = new DBConn(con1.getConnection());
        try {
            cdb.setStatement();
        } catch (Exception ex) {
            System.out.println(ex);
        }

        //out.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        try {
            mrequest = new MultipartFormDataRequest(request);
            hospital_code = session.getAttribute("HOSPITAL_CODE").toString();
            user_id = session.getAttribute("USER_ID").toString();
            upload_path = getIP("IP_UPLOAD_FILE",hospital_code);
            if ("date".equalsIgnoreCase(mrequest.getParameter("selectFileType").toString())) {
                //select from date
                dt = mrequest.getParameter("INTERFACE_DATE");
                if (mrequest.getParameter("INTERFACE_PROCESS").equals("ImportTransaction")) {
                    ip = getIP("IP_INTERFACE_TRANSACTION",hospital_code);
                    source_file = ip + "DF" + hospital_code + "." + JDate.saveDate(dt);
                } else if (mrequest.getParameter("INTERFACE_PROCESS").equals("ImportVerifyTransaction")) {
                    ip = getIP("IP_INTERFACE_TRANSACTION_RESULT",hospital_code);
                    source_file = ip + "DFVerify" + hospital_code + "." + JDate.saveDate(dt);
                } else if (mrequest.getParameter("INTERFACE_PROCESS").equals("ImportARTransaction")) {
                    ip = getIP("IP_INTERFACE_AR_TRANSACTION",hospital_code);
                    source_file = ip + "ARDF." + JDate.saveDate(dt);
                } else if(mrequest.getParameter("INTERFACE_PROCESS").equals("ImportExpense")){
                    ip = getIP("IP_INTERFACE_CO",hospital_code);
                    source_file = ip + "DFCO" + hospital_code + "." + JDate.saveDate(dt);
                } else { /*developer not implement code here*/ }
            } else {
                //select from file
                filename = mrequest.getParameter("SOURCE_FILE");
                filename = filename.replace("\\", "|");
                String[] fname = filename.split("[|]");

                if(Variables.IS_WINDOWS){
                    source_file = upload_path+fname[fname.length - 1];
                    source_file = source_file.replace("/", "\\");
                }else{ 
                	upload_path = getServletConfig().getServletContext().getRealPath("")+"/reports/output/";
                    source_file = upload_path+fname[fname.length - 1];
                }
                System.out.println(Variables.IS_TEST ? source_file : "");
                File f = new File(source_file);
                try{
                    if (f.exists()) {
                        f.delete();
                        //System.out.println("File to be delete");
                    }                	
                }catch(Exception e){
                	System.out.println("File Exits Exception : "+e);
                }
                UploadBean up = new UploadBean();
                up.setFolderstore(upload_path);
                up.store(mrequest, "FILE_INTERFACE");
            }
            out.println(source_file);
        } catch (Exception ex) {
        	System.out.println("Import File Servlet Error : "+ex);
        }
        
        if(mrequest.getParameter("INTERFACE_PROCESS").equals("ImportTransaction")){
        	it.setDate(dt);
        	it.setUserName(user_id);
        	it.setHospitalCode(hospital_code);
        	if(Variables.IS_TEST){
        		System.out.println("Start Import Transaction : " + JDate.getTime());
        	}
            if(it.insertData(source_file,con1)){
            	if(Variables.IS_TEST){
            		System.out.println("Finish Import Transaction : "+JDate.getTime());
            	}
                if(inmb.ImportNewMaster(it.getBillDate(), hospital_code, cdb)){
                    out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                    out.println("<script language='javascript'>");
                    out.println("alert('Import Transaction "+it.getMessage()+"');");
                    out.println("</script>");
                    out.println("</body>");
                    out.close();  
                }else{
                    out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                    out.println("<script language='javascript'>");
                    out.println("alert('Cannot Auto Insert Master Data'"+inmb.getMessage()+");");
                    out.println("</script>");
                    out.println("</body>");
                    out.close(); 
                }
                              
            }else{
                out.println("<body>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Transaction Error : "+it.getMessage()+" / Source : "+source_file+"');");
                out.println("</script>");                
                out.println("</body>");
                out.close();
            }
            
        }else if(mrequest.getParameter("INTERFACE_PROCESS").equals("ImportVerifyTransaction")){
        	idr.setUserName(user_id);
        	idr.setHospitalCode(hospital_code);
            if(idr.insertData(source_file,con1)){
                out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Verify "+idr.getMessage()+"');");
                out.println("</script>");
                out.println("</body>");
                out.close();
            }else{
                out.println("<body>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Verify Error : "+idr.getMessage()+" / Source : "+source_file+"');");
                out.println("</script>");                
                out.println("</body>");
                out.close();
            }
        }else if(mrequest.getParameter("INTERFACE_PROCESS").equals("ImportARTransaction")){
        	iar.setUserName(user_id);
        	iar.setHospitalCode(hospital_code);
            if(iar.insertData(source_file,con1)){
                out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                out.println("<script language='javascript'>");
                out.println("alert('Import ERP Recepit "+iar.getMessage()+"');");
                out.println("</script>");
                out.println("</body>");
                out.close();
            }else{
                out.println("<body>");
                out.println("<script language='javascript'>");
                out.println("alert('Import ERP Recepit Error "+iar.getMessage()+" / Source : "+source_file+"');");
                out.println("</script>");                
                out.println("</body>");
                out.close();
            }
        }else if(mrequest.getParameter("INTERFACE_PROCESS").equals("ImportGuarantee")){
            if(igu.insertData(source_file,con1)){
                out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Guarantee "+igu.getMessage()+"');");
                out.println("</script>");
                out.println("</body>");
                out.close();
            }else{
                out.println("<body>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Guarantee Error "+igu.getMessage()+" / Source : "+source_file+"');");
                out.println("</script>");                
                out.println("</body>");
                out.close();
            }
        }else if(mrequest.getParameter("INTERFACE_PROCESS").equals("ImportExpense")){
            if(iex.insertData(source_file,con1)){
                out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                out.println("<script language='javascript'>");
                out.println("alert('Import C/O "+iex.getMessage()+"');");
                out.println("</script>");
                out.println("</body>");
                out.close();
            }else{
                out.println("<body>");
                out.println("<script language='javascript'>");
                out.println("alert('Import C/O Error : "+iex.getMessage()+" / Source : "+source_file+"');");
                out.println("</script>");
                out.println("</body>");
                out.close();
            }
        }else if(mrequest.getParameter("INTERFACE_PROCESS").equals("ImportPatho")){
            if(it.insertData(source_file,con1)){
                if(inmb.ImportNewMaster(it.getBillDate(), hospital_code, cdb)){
                    out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                    out.println("<script language='javascript'>");
                    out.println("alert('Import Patho "+it.getMessage()+"');");
                    out.println("</script>");
                    out.println("</body>");
                    out.close();  
                }else{
                    out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                    out.println("<script language='javascript'>");
                    out.println("alert('Cannot Auto Insert Master Data'"+inmb.getMessage()+" / Source : "+source_file+"');");
                    out.println("</script>");
                    out.println("</body>");
                    out.close(); 
                }
            }else{
                out.println("<body>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Patho Error : "+it.getMessage()+" / Source : "+source_file+"');");
                out.println("</script>");                
                out.println("</body>");
                out.close();
            }
        }else if(mrequest.getParameter("INTERFACE_PROCESS").equals("ImportExpenseExcel")){
        	iee.setUserName(session.getAttribute("USER_ID").toString());
        	iee.setHospital(session.getAttribute("HOSPITAL_CODE").toString());
            if(iee.insertData(source_file,con1)){
                out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Expense "+iee.getMessage()+"');");
                out.println("</script>");
                out.println("</body>");
                out.close();
            }else{
                out.println("<body>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Expense Error : "+iee.getMessage()+" / Source : "+source_file+"');");
                out.println("</script>");
                out.println("</body>");
                out.close();
            }
        }else if(mrequest.getParameter("INTERFACE_PROCESS").equals("ImportTimeTable")){
        	itt.setUserName(session.getAttribute("USER_ID").toString());
        	itt.setHospital(session.getAttribute("HOSPITAL_CODE").toString());
            if(itt.insertData(source_file,con1)){
                out.println("<body bgcolor=\"#dde4e8\"><p><p>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Time Table "+itt.getMessage()+"');");
                out.println("</script>");
                out.println("</body>");
                out.close();
            }else{
                out.println("<body>");
                out.println("<script language='javascript'>");
                out.println("alert('Import Time Table Error : "+itt.getMessage()+" / Source : "+source_file+"');");
                out.println("</script>");
                out.println("</body>");
                out.close();
            }
        }else{}
        con1.Close();
        cdb.closeDB("");
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
